<template>
  <div class="lost-page">
    <!-- 导航栏 -->
    <NavBar title="失物招领">
      <template #right>
        <van-icon name="plus" size="20" color="white" @click="goToAdd" />
      </template>
    </NavBar>
    
    <!-- 内容区域 -->
    <div class="page-content">
      <!-- 分类标签 -->
      <div class="category-tabs">
        <van-tabs v-model:active="activeType" @change="handleTypeChange">
          <van-tab title="全部" name="all" />
          <van-tab title="寻物启事" name="lost" />
          <van-tab title="失物招领" name="found" />
        </van-tabs>
      </div>
      
      <!-- 搜索栏 -->
      <div class="search-bar">
        <van-search
          v-model="searchKeyword"
          placeholder="搜索失物信息..."
          @search="handleSearch"
          @clear="handleClear"
        />
      </div>
      
      <!-- 列表 -->
      <div class="lost-list">
        <div 
          v-for="lost in lostList" 
          :key="lost.id"
          class="lost-item card"
          @click="goToDetail(lost.id)"
        >
          <!-- 类型标签 -->
          <div class="lost-header">
            <van-tag 
              :type="lost.lostType === 'lost' ? 'warning' : 'success'" 
              size="mini"
            >
              {{ lost.lostType === 'lost' ? '寻物启事' : '失物招领' }}
            </van-tag>
            <div class="time">{{ formatTime(lost.createTime) }}</div>
          </div>
          
          <!-- 内容 -->
          <div class="lost-content">
            <div class="title">{{ lost.title }}</div>
            <div class="content">{{ lost.content }}</div>
            
            <!-- 失物信息 -->
            <div class="lost-info">
              <div class="info-item">
                <span class="label">丢失地点:</span>
                <span class="value">{{ lost.location }}</span>
              </div>
              <div class="info-item">
                <span class="label">联系方式:</span>
                <span class="value contact">{{ lost.contactWay }}</span>
              </div>
              <div class="info-item" v-if="lost.reward">
                <span class="label">酬谢:</span>
                <span class="value reward">{{ lost.reward }}</span>
              </div>
            </div>
            
            <!-- 图片 -->
            <div class="images" v-if="hasImages(lost)">
              <img 
                v-if="lost.pic1"
                :src="lost.pic1" 
                alt="图片"
                class="content-image"
                @click.stop="previewImage(getImageList(lost), 0)"
              />
              <img 
                v-if="lost.pic2"
                :src="lost.pic2" 
                alt="图片"
                class="content-image"
                @click.stop="previewImage(getImageList(lost), 1)"
              />
              <img 
                v-if="lost.pic3"
                :src="lost.pic3" 
                alt="图片"
                class="content-image"
                @click.stop="previewImage(getImageList(lost), 2)"
              />
            </div>
          </div>
          
          <!-- 底部操作 -->
          <div class="lost-footer">
            <div class="user-info">
              <img :src="lost.userAvatar || '/images/default-avatar.png'" alt="头像" class="avatar" />
              <span class="nickname">{{ lost.userNickname }}</span>
            </div>
            <div class="stats">
              <span class="stat-item">
                <van-icon name="eye-o" size="14" />
                {{ lost.viewCount }}
              </span>
              <span class="stat-item">
                <van-icon name="chat-o" size="14" />
                {{ lost.commentCount }}
              </span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 加载更多 -->
      <div class="load-more" v-if="hasMore">
        <van-button 
          :loading="loading" 
          @click="loadMore"
          type="default"
          size="small"
        >
          {{ loading ? '加载中...' : '加载更多' }}
        </van-button>
      </div>
      
      <!-- 空状态 -->
      <van-empty 
        v-if="!loading && lostList.length === 0"
        description="暂无失物信息"
        image="search"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showImagePreview, showToast } from 'vant'
import NavBar from '@/components/Common/NavBar.vue'
import { lostApi } from '@/api/lost'
import type { LostPost } from '@/types'
import { formatTime } from '@/utils/time'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const activeType = ref('all')
const lostList = ref<LostPost[]>([])
const loading = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = 10

// 加载列表数据
const loadList = async (isRefresh = false) => {
  if (loading.value) return
  
  loading.value = true
  
  try {
    const params = {
      pageNo: isRefresh ? 0 : currentPage.value,  // 从0开始
      pageSize: pageSize,
      str: searchKeyword.value || undefined,  // 搜索关键词
      type: activeType.value === 'all' ? undefined : (activeType.value === 'lost' ? '0' : '1')  // 类型转换为字符串
    }
    
    const response = await lostApi.getList(params)
    
    if (response.code === 1 && response.data) {
      const { list, total } = response.data
      
      if (isRefresh) {
        lostList.value = list || []
        currentPage.value = 0
      } else {
        lostList.value.push(...(list || []))
      }
      
      hasMore.value = (list || []).length === pageSize
      currentPage.value++
    } else {
      showToast(response.msg || '加载失败')
    }
  } catch (error: any) {
    console.error('加载失物招领列表失败:', error)
    if (error.message?.includes('401') || error.message?.includes('未授权')) {
      showToast('请先登录')
      // 可以跳转到登录页
    } else {
      showToast('加载失败')
    }
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 0
  loadList(true)
}

// 清除搜索
const handleClear = () => {
  searchKeyword.value = ''
  currentPage.value = 0
  loadList(true)
}

// 类型切换
const handleTypeChange = () => {
  currentPage.value = 0
  loadList(true)
}

// 加载更多
const loadMore = () => {
  loadList()
}

// 跳转到发布页面
const goToAdd = () => {
  router.push('/lost/add')
}

// 跳转到详情页面
const goToDetail = (id: string) => {
  router.push(`/lost/${id}`)
}

// 检查是否有图片
const hasImages = (item: any) => {
  return item.pic1 || item.pic2 || item.pic3
}

// 获取图片列表
const getImageList = (item: any) => {
  const images = []
  if (item.pic1) images.push(item.pic1)
  if (item.pic2) images.push(item.pic2)
  if (item.pic3) images.push(item.pic3)
  return images
}

// 预览图片
const previewImage = (images: string[], startPosition: number) => {
  showImagePreview({
    images,
    startPosition,
    closeable: true
  })
}

// 页面加载时获取数据
onMounted(() => {
  loadList(true)
})
</script>

<style scoped>
.lost-page {
  min-height: 100vh;
  background-color: #f1f1f1;
}

.page-content {
  padding: 0 16px 16px;
}

.category-tabs {
  background: white;
  border-radius: 8px;
  margin: 16px 0;
  overflow: hidden;
}

.search-bar {
  background: white;
  border-radius: 8px;
  margin-bottom: 16px;
  overflow: hidden;
}

.lost-list {
  margin-bottom: 16px;
}

.lost-item {
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.lost-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.lost-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.time {
  font-size: 12px;
  color: #999;
}

.lost-content {
  margin-bottom: 12px;
}

.title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
  line-height: 1.4;
}

.content {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.lost-info {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 12px;
  margin-bottom: 8px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
  font-size: 14px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  color: #666;
  width: 80px;
  flex-shrink: 0;
}

.value {
  color: #333;
  flex: 1;
}

.contact {
  color: #636DEA;
}

.reward {
  color: #e74c3c;
  font-weight: 500;
}

.images {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  position: relative;
}

.content-image {
  width: 80px;
  height: 80px;
  border-radius: 6px;
  object-fit: cover;
  cursor: pointer;
}

.more-images {
  width: 80px;
  height: 80px;
  border-radius: 6px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  position: absolute;
  top: 0;
  right: 0;
}

.lost-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  object-fit: cover;
}

.nickname {
  font-size: 14px;
  color: #333;
}

.stats {
  display: flex;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #999;
}

.load-more {
  text-align: center;
  padding: 16px 0;
}
</style>